package cn.com.dstz.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;

import cn.com.dstz.admin.constants.Constants;
import cn.com.dstz.security.encoder.Md5PwdEncoder;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.NumberUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.base.action.BaseAction;

/**
 * 居间管理
 * 只有admin和顶级居间才可以进行居间管理,即添加居间操作
 * 
 * 
 * 添加居间的时候，首先是由系统管理员进行添加， 所以居间中的topaid（即adminid） 应该为0，faid也为0，而且系统管理员并不能添加二级居间，如果允许的话，将会造成数据错乱
 * 然后顶级居间添加的顶级居间的时候， topaid 为当前登录用户的ID, faid 为 0
 * 顶级居间添加二级居间的是否， topaid 为当前登录用户的ID， faid 为 当前居间的ID
 * 
 * ========
 * 1. 系统管理员查询出全部的居间
 * 2. 顶级居间  查询自己添加的居间
 * 3. 顶级居间搜索条件： (非自己添加的) 所有， 是否可以查询顶级居间，是否可以查询次级居间，自己
 * 
 * 
 * 
 * @author 叶装装
 *
 */
public class IntermediateAct extends BaseAction{

	private static final String DEFAULT_PASSWORD = "dstz.com.cn"; // 默认的密码
	private static final String DEFAULT_ADMIN_SUFFIX = "_dstz"; // 默认的后缀
	
	private String getListSQL( ){
		String sql = "select count(m.id) as membercount, ab.id as id, ab.username as username, ab.name as name,";
		sql += "ab.telephone as telephone, ab.sjphone as sjphone, ab.address as address,";
		sql += "ab.email as email, ab.khqq as khqq, ab.jsqq as jsqq, ab.kaihqq as kaihqq, ab.hzqq as hzqq, ab.tsqq as tsqq,";
		sql += "ab.info as info, ab.homepage as homepage, ab.status as status, ab.faid as faid,ab.admincount as admincount,ab.parentname as parentname  ";
		sql += "from ( select aa.username, ag.*, count(aa.id) as admincount, ag2.name as parentname from  dstzagent ag ";
		sql += "  left outer join dstzadmin aa on ag.id = aa.topaid left outer join dstzagent ag2 on ag2.id = ag.faid ";
		sql += " where aa.aid != 0 group by ag.id ) as ab left outer join  dstzmember m on m.topaid = ab.id where 1=1";
		
		return sql;
	}
	
	private void fillMap( int config, Map< String, Object > admin, Map< String, Object > valueMap ){
		// 查看自己
		if( config == 0 ){
			valueMap.put( "aid", admin.get( "id" ) );
		}else if( config == 1 ){		// 查看所有
			valueMap.put( "aid", admin.get( "id" ) );
			valueMap.put( "aid2", admin.get( "id" ) );
		}else if( config == 2 ){		// 查看次级
			valueMap.put( "aid", admin.get( "id" ) );
			valueMap.put( "aid2", admin.get( "id" ) );
		}else if( config == 3 ){	// 查看喊单
			valueMap.put( "aid", admin.get( "id" ) );
			valueMap.put( "aid2", admin.get( "id" ) );
		}
	}

	private static final Map< Integer, String > SQLMap;
	static{
		SQLMap = new HashMap< Integer, String > ( );
		SQLMap.put( 0, " and ab.topaid=:aid " );
		SQLMap.put( 1, " and ab.topaid in ( select id from dstzadmin where  aid = :aid ) or ab.topaid = :aid2  " );
		SQLMap.put( 2, " and ab.faid = 0 and ( ab.topaid in ( select id from dstzadmin where  aid = :aid ) or ab.topaid = :aid2  ) " );
		SQLMap.put( 3, " and ab.faid > 0  and ( ab.topaid in ( select id from dstzadmin where  aid = :aid ) or ab.topaid = :aid2 ) " );
	}
	
	
	
	public void list( ){
		
		Map< String, Object > admin = this.getEntityInSession( cn.com.dstz.web.constants.Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		String countSQL = "select count(*) as a from (select aa.username, ag.*,  ag2.name as parentname from  dstzagent ag  left outer join dstzadmin aa on ag.id = aa.aid " +
				"left outer join dstzagent ag2 on ag2.id = ag.faid group by ag.id ) as ab where 1=1";
		
		String sql = getListSQL( );
		
		if( level > 0 ){
			
			int config = NumberUtils.getInt( ActionUtils.getConfig( admin ).get( "config_agent" ).toString( ), 0 );//ActionUtils.getConfigValue( admin, "config_agent" );
			String query = SQLMap.get( config );
			
			countSQL += query;
			sql += query;
		
			this.fillMap( config, admin, valueMap );
			
			String statusSql = " and ab.status=:status ";
			sql += statusSql;
			countSQL += statusSql;
			
			valueMap.put( "status", cn.com.dstz.admin.constants.Constants.AGENT_STATUS_NORMAL );
		}
		
		sql += " group by ab.id";

		Map< String, Type > aliasMap = DataBaseUtils.getAlias( new String[]{
				"membercount", "id", "username", "name",  "telephone",  "sjphone","address","email","khqq","jsqq","kaihqq","hzqq","tsqq","info","homepage","status","faid",
				"admincount", "parentname"
		}, new Type[]{
				Hibernate.INTEGER, Hibernate.INTEGER, Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,
				Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,Hibernate.STRING,
				Hibernate.BYTE, Hibernate.INTEGER, Hibernate.INTEGER ,Hibernate.STRING,
		} );
		
		this.responseToJsonObject( this.paginationBySQL( sql, countSQL, valueMap, null, aliasMap ) );
		return;
	}
	
	
	/**
	 * 转到居间添加页面
	 * @return
	 */
	public String toadd( ){
		// 是否允许添加顶级居间的问题，
		return "add";
	}
	
	
	public void add( ){
		
		Map< String, Object > admin = this.getEntityInSession( cn.com.dstz.web.constants.Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		int validSaveOrUpdate = validSaveOrUpdate( 0 );
		Map< String, Object > jsonMap = new HashMap< String, Object >( );
		
		if( validSaveOrUpdate > 0 ){
			
			jsonMap.put( "success", 1 );
			jsonMap.put( "msg", validSaveOrUpdate );
			
			this.responseToJsonObject( jsonMap );
			return;
		}
		
		Map< String, Object > saveData = getSaveOrUpdateData( );
		saveData.put( "status", Constants.AGENT_STATUS_NORMAL );
		saveData.put( "version", 1 );
		
		// 系统管理员添加的是顶级居间，faid 为0, 还有顶级居间可以添加顶级居间，靠topIntermediate来判断
		Object faid = 0;	
		
		// 判断顶级居间标识是否为空, 如果为空表示的为非顶级
		if( topIntermediate == null ){
			faid = admin.get( "topaid" );	// 上级居间的id
		}
		
		saveData.put( "faid", faid );
		saveData.put( "topaid",  level == 0 ? 0 : admin.get( "id" ) );	//	当前管理员的ID
		
		int save = baseService.save( "dstzagent", saveData, true );
		
		if( save <= 0 ){
			jsonMap.put( "success", 1 );
			jsonMap.put( "msg", 12 );
			
			this.responseToJsonObject( jsonMap );
		}
		
		Map< String, Object > adminData = this.getAdminData( save, admin );
		
		save = baseService.save( "dstzadmin", adminData );
		
		this.addLog( save, "agent", 0, name );
		
		jsonMap.put( "success", save > 0 ? 0 : -1 );
		jsonMap.put( "username", adminData.get( "username" ) );
		jsonMap.put( "password", valid( isAuto, 0 ) ? "" : DEFAULT_PASSWORD );
		
		this.responseToJsonObject( jsonMap );
		return;
		
	}
	
	public String toedit( ){
		
		int validUpdate = validUpdate( 0 );
		
		if( validUpdate > 0 ){
			alertMsg(null);
			return "edit";
		}
		
		String sql = "select ag.*, g.name as groupname, a.username from dstzgroup g, dstzadmin a left outer join dstzagent ag on a.topaid = ag.id where a.groupid = g.id and ag.id=" + id;
		Map< String, Object > data = baseService.getData( sql );
		
		if( data == null || data.isEmpty( ) ){
			alertMsg(null);
			return "edit";
		}
		
		getRequest( ).setAttribute( "data", data );
		
		
		
		return "edit";
	}
	
	public void edit( ){
		
		int validUpdate = validUpdate( 1 );
		
		if( validUpdate > 0 ){
			this.ajaxResponse( validUpdate );
			return;
		}
		
		int update = baseService.update( "dstzagent", getSaveOrUpdateData(), DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		}) );
		
		this.addLog( update, "agent", 1, "ID：" + id );
		this.ajaxResponse( update > 0 ? 0 : -1 );
		return;
	}
	
	public void delete( ){
		String ids = getParameter( "ids" );
		
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( cn.com.dstz.web.constants.Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin );
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						
						if( level == 0 ){
							updateSqlList.add( "delete from dstzagent where id =" + id); // 如果执行删除的话，还要删除管理员
							updateSqlList.add( "delete from dstzadmin where topaid=" + id );
							
						}else{
							updateSqlList.add( "update dstzagent set status = " + cn.com.dstz.admin.constants.Constants.AGENT_STATUS_DISABLED + " where id =" + id );
						}
					}
				}
				
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				
				this.addLog( del, "agent", 2, ids );
				
			}
		}
		
	}
	
	private int validUpdate( int type ){
		if( id == null || id == 0 ){
			return 10;
		}
		
		if( type == 0 ){
			return 0;
		}
		
		int commonValid = commonValid( );
		
		if( commonValid > 0 ){
			return commonValid;
		}
		
		if( !StringUtils.equals( oldname, name )){
			int dbValidByAgent = dbValid( 0 );
			if( dbValidByAgent > 0 ){
				return 9;
			}
		}
		
		
		return 0;
	}
	
	private Map< String, Object > getSaveOrUpdateData( ){
		return DataBaseUtils.getData( new String[]{
				"name",	"telephone",	"sjphone",	"address",	"email",
				"khqq",	"jsqq",	"kaihqq",		"hzqq",	"tsqq",	"info",	"homepage",
				
		}, new Object[]{
				name,	tel,	contactuser,	address,	email,	serviceQQ,	technologyQQ,	openAccountQQ,	cooperationQQ,	complaintsQQ,	description,		homepage
		} );
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		
		if( valid( isAuto, 0 ) ){
			if( ValidUtils.validLength( username, 3, 20 )){
				return 9;
			}
			
			if( StringUtils.isBlank( password )){
				return 10;
			}
			
			int dbValidByAdmin = dbValid( 1 );
			if( dbValidByAdmin > 0 ){
				return 13;
			}
		}
		
		int commonValid = commonValid( );
		
		if( commonValid > 0 ){
			return commonValid;
		}
		
		
		int dbValidByAgent = dbValid( 0 );
		if( dbValidByAgent > 0 ){
			return 11;
		}
		
		return 0;
		
	}
	
	private int commonValid( ){
		
		if( ValidUtils.validLength( name, 3, 32 )){
			return 1;
		}
		
		if( ValidUtils.validLength( address, 3, 100 )){
			return 2;
		}
		
		if( ValidUtils.validLength( contactuser, 2, 11 )){
			return 3;
		}
		
		if( ValidUtils.validLength( email, 1, 50 )){
			return 4;
		}
		
		// 这个是联系电话
		if( ValidUtils.validLength( tel, 1, 13 )){
			return 5;
		}
		
		if( ValidUtils.validLength( homepage, 3, 50 )){
			return 6;
		}
		
		if( ValidUtils.validLength( serviceQQ, 5, 15 )){
			return 7;
		}
		
		if( ValidUtils.validLength( technologyQQ, 5, 15 )){
			return 7;
		}
		
		if( ValidUtils.validLength( openAccountQQ, 5, 15 )){
			return 7;
		}
		
		if( ValidUtils.validLength( cooperationQQ, 5, 15 )){
			return 7;
		}
		
		if( ValidUtils.validLength( complaintsQQ, 5, 15 )){
			return 7;
		}
		
		if( StringUtils.isNotBlank( description ) && description.length( ) > 200 ){
			return 8;
		}
		
		return 0;
	}
	
	private int dbValid( int validType ){
		
		return validType == 0 ? 
											baseService.countBySQL( "select count(*) as a from dstzagent where name=:name", DataBaseUtils.getData( new String[]{
											"name"
											}, new Object[]{
													name
											} ))
											:
											baseService.countBySQL( "select count(*) as a from dstzadmin where username=:username",  DataBaseUtils.getData( new String[]{
												"username"
											}, new Object[]{
													username
											} ) );
		
	}
	
	private Map< String, Object > getAdminData( int agentId, Map< String, Object > admin ){
		Map< String, Object > adminData = new HashMap< String, Object >( );
		// 如果勾选了，表示为自己填写
		if( valid( isAuto, 0 ) ){
			adminData.put( "username", username );
			adminData.put( "password", password );
		}else{
			adminData.put( "username", agentId + DEFAULT_ADMIN_SUFFIX );
			adminData.put( "password", pwdEncoder.md5( DEFAULT_PASSWORD ) );
		}
		
		int level = ActionUtils.getAdminLevel( admin );
		
		adminData.put( "status", Constants.ADMIN_STATUS_NORMAL );
		adminData.put( "groupid", getGroupId( ) );
		
		adminData.put( "topaid", agentId );			// 这个标识是属于哪个居间商的
		adminData.put( "aid", level == 0 ? 0 : admin.get( "id" ) ); 						  
		
		adminData.put( "hasagent", 1 );	// 这个表示是有居间的管理员账户
		
		return adminData;
	}
	
	private boolean valid( Integer validColumn, Integer validNum ){
		if( validColumn != null && validColumn == validNum ){
			return true;
		}
		
		return false;
	}
	
	/**
	 * 获取分组ID
	 * 是顶级居间的时候， 自动分配到组2，
	 * 不是的话， 为3
	 * @return
	 */
	private Integer getGroupId( ){
		if( valid( topIntermediate, 1 )){
			return topIntermediateGroup;
		}
		
		return secondIntermediateGroup;
	}

	private Integer id;
	
	private String name;
	private String address;
	private String contactuser;
	private String email;
	private String tel;
	private String homepage;
	private String serviceQQ;
	private String technologyQQ;
	private String openAccountQQ;
	private String cooperationQQ;
	private String complaintsQQ;
	private String description;
	private String oldname;
	
	private String username;
	private String password;
	
	private Integer isAuto;   // 是否自动生成账号密码
	/**是否顶级居间*/
	private Integer topIntermediate;  
	
	// 顶级居间和次级居间的 分组ID
	private Integer topIntermediateGroup; 
	private Integer secondIntermediateGroup; 
	
	public String getUsername( ) {
		return username;
	}

	public void setUsername( String username ) {
		if( StringUtils.isNotBlank( username )){
			username = decode( username );
		}
		this.username = username;
	}

	public String getPassword( ) {
		return password;
	}

	public void setPassword( String password ) {
		if( StringUtils.isNotBlank( password )){
			password = pwdEncoder.md5( password );
		}
		this.password = password;
	}

	public Integer getTopIntermediate( ) {
		return topIntermediate;
	}

	public void setTopIntermediate( Integer topIntermediate ) {
		this.topIntermediate = topIntermediate;
	}

	public Integer getIsAuto( ) {
		return isAuto;
	}

	public void setIsAuto( Integer isAuto ) {
		this.isAuto = isAuto;
	}

	public Integer getTopIntermediateGroup( ) {
		return topIntermediateGroup;
	}

	public void setTopIntermediateGroup( Integer topIntermediateGroup ) {
		this.topIntermediateGroup = topIntermediateGroup;
	}

	public Integer getSecondIntermediateGroup( ) {
		return secondIntermediateGroup;
	}

	public void setSecondIntermediateGroup( Integer secondIntermediateGroup ) {
		this.secondIntermediateGroup = secondIntermediateGroup;
	}

	public String getName( ) {
		return name;
	}

	public void setName( String name ) {
		if( StringUtils.isNotBlank( name )){
			name = decode( name );
		}
		this.name = name;
	}
	

	public String getAddress( ) {
		return address;
	}

	public void setAddress( String address ) {
		if( StringUtils.isNotBlank( address )){
			address = decode ( address );
		}
		this.address = address;
	}

	public String getContactuser( ) {
		return contactuser;
	}

	public void setContactuser( String contactuser ) {
		if( StringUtils.isNotBlank( contactuser )){
			contactuser = decode ( contactuser );
		}
		this.contactuser = contactuser;
	}

	public String getEmail( ) {
		return email;
	}

	public void setEmail( String email ) {
		if( StringUtils.isNotBlank( email )){
			email = decode( email );
		}
		this.email = email;
	}

	public String getTel( ) {
		return tel;
	}

	public void setTel( String tel ) {
		this.tel = tel;
	}

	public String getHomepage( ) {
		return homepage;
	}

	public void setHomepage( String homepage ) {
		this.homepage = homepage;
	}

	public String getServiceQQ( ) {
		return serviceQQ;
	}

	public void setServiceQQ( String serviceQQ ) {
		this.serviceQQ = serviceQQ;
	}

	public String getTechnologyQQ( ) {
		return technologyQQ;
	}

	public void setTechnologyQQ( String technologyQQ ) {
		this.technologyQQ = technologyQQ;
	}

	public String getOpenAccountQQ( ) {
		return openAccountQQ;
	}

	public void setOpenAccountQQ( String openAccountQQ ) {
		this.openAccountQQ = openAccountQQ;
	}

	public String getCooperationQQ( ) {
		return cooperationQQ;
	}

	public void setCooperationQQ( String cooperationQQ ) {
		this.cooperationQQ = cooperationQQ;
	}

	public String getComplaintsQQ( ) {
		return complaintsQQ;
	}

	public void setComplaintsQQ( String complaintsQQ ) {
		this.complaintsQQ = complaintsQQ;
	}

	public String getDescription( ) {
		return description;
	}

	public void setDescription( String description ) {
		if( StringUtils.isNotBlank( description )){
			description = decode ( description );
		}
		this.description = description;
	}
	
	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}

	
	public String getOldname( ) {
		return oldname;
	}



	public void setOldname( String oldname ) {
		if( StringUtils.isNotBlank( oldname )){
			oldname = decode( oldname );
		}
		this.oldname = oldname;
	}

	private Md5PwdEncoder pwdEncoder;
	
	public Md5PwdEncoder getPwdEncoder( ) {
		return pwdEncoder;
	}

	public void setPwdEncoder( Md5PwdEncoder pwdEncoder ) {
		this.pwdEncoder = pwdEncoder;
	}

	private static final long serialVersionUID = 1L;

	
}
